<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;


use App\Model\Coupon;
use App\Model\CouponRecord;
use App\Model\Device;
use App\Model\Station;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Qiniu\Http\Request;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class HomeCouponController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;


    #[Inject]
    protected Coupon $coupon;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**活动列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function list(RequestInterface $request): ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $page = $request->inputs(['page', 'limit', 'is_active', 'type','keyword']);
        $data['list'] = $this->coupon->where(function ($query) use ($page,$info) {
            if (isset($page['is_active']) && $page['is_active'] != '') {
                $query->where('is_active', $page['is_active']);
            }
            if (isset($page['keyword']) && $page['keyword']) {
                $query->where('type','like','%'.$page['keyword'].'%');
            }
            if (isset($page['type']) && $page['type'] != '') {
                $query->where('type', Coupon::TYPE_MAP[$page['type']]);
            }
            $query->where('distributor_id',$info['id']);
        })->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get(['id','type','fee','days','content','is_active','content','images','start_date','end_date'])->toArray();
        $data['total'] = $this->coupon->where(function ($query) use ($page,$info) {
            if (isset($page['is_active']) && $page['is_active'] != '') {
                $query->where('is_active', $page['is_active']);
            }
            if (isset($page['type']) && $page['type'] != '') {
                $query->where('type', Coupon::TYPE_MAP[$page['type']]);
            }
            if (isset($page['keyword']) && $page['keyword']) {
                $query->where('type','like','%'.$page['keyword'].'%');
            }
            $query->where('distributor_id',$info['id']);
        })->count();
        $time = time();
        foreach($data['list'] as $k => $v){
            $start = strtotime($v['start_date']);
            $end = strtotime($v['end_date']);
            $data['list'][$k]['check_time'] = [];
            if($time < $start){
                $data['list'][$k]['check_time']['label'] =  '活动未开始';
                $data['list'][$k]['check_time']['status'] =  0;
            }elseif ($time > $end){
                $data['list'][$k]['check_time']['label']=  '活动已结束';
                $data['list'][$k]['check_time']['status'] = 1;
            }else{
                $data['list'][$k]['check_time']['label'] =  '活动进行中';
                $data['list'][$k]['check_time']['status'] = 2;
            }
        }
        return $this->success($data);
    }

    /**修改活动状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request):ResponseInterface{
        $couponId = $request->input('coupon_id');
        $status = $request->input('is_active',0,'int');
        if(!$couponId){
            return $this->error(1001,'优惠券信息不存在');
        }

        $couponModel = $this->coupon->where('id',$couponId)->first();
        if(!$couponModel){
            return $this->error(1001,'优惠券信息不存在');
        }
        try{
            if($status>0){
                $this->coupon->where('distributor_id',$couponModel->distributor_id)
                    ->where('type',$couponModel->type)
                    ->update(['is_active'=>0]);
            }
            $couponModel->is_active = $status;
            $couponModel->save();
            return $this->success();
        }catch (\Exception $e){
            return $this->error(1002,'操作繁忙 请稍后重试');
        }
    }
    /**添加营销活动
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $params = $request->inputs(['id','type', 'start_date', 'end_date', 'fee', 'days', 'quantity', 'is_active', 'content', 'images', 'devices', 'moneys']);
        if (isset($params['devices'])) {
            $devices = json_decode($params['devices']);
            $devices  = array_unique($devices);
        } else {
            if(!$params['devices']){
                $devices = [];
            }else{
                $devices = $params['devices'];
            }
        }
        unset($params['devices']);
        if (isset($params['moneys'])) {
            $moneys = json_decode($params['moneys'], true);
        } else {
            if(!$params['moneys']) {
                $moneys = [];
            }else{
                $moneys =$params['moneys'];
            }
        }
        unset($params['moneys']);
        $params['distributor_id'] = $info['id'];
        $type = $params['type'];
        $params['type'] = Coupon::TYPE_MAP[$params['type']];
//            try{
        if(isset($params['id']) && $params['id']){
            $active = Coupon::where('id',$params['id'])->save($params);
        }else{
            $active = Coupon::create($params);
        }
        if (!$active) {
            return $this->error('1003', '创建失败 请稍后重试');
        }
//        $endtime = strtotime($params['end_date']);
//        $now = time();
            $cacheKey = Coupon::COUPON_DEVICE_CACHE . $active->id;
            foreach ($devices as $k => $v) {
                $this->redis->sAdd($cacheKey, $v);
            }
//            $this->redis->expire($cacheKey, $endtime - $now);
        if ($type == Coupon::TYPE_RECHARGE_RECEIVE) {
                $cacheKey = Coupon::COUPON_MONEY_CACHE . $active->id;
                foreach ($moneys as $k => $v) {
                    $this->redis->hSet($cacheKey, (string)$k, $v);
                }
//                $this->redis->expire($cacheKey, $endtime - $now);
        }
        return $this->success(msg: '添加活动成功');
//            }catch (\Exception $e){
//                return $this->error('1002','操作繁忙 请稍后重试');
//            }
        return $this->error(code: '1002', msg: '操作繁忙 请稍后重试');
    }

    /**活动详情
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function detail(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $couponId = $request->input('coupon_id');
        $couponModel = $this->coupon->where('id',$couponId)->first()->toArray();
        if($couponModel){
            $deviceKey = Coupon::COUPON_DEVICE_CACHE . $couponId;
            $couponModel['devices'] = $this->redis->sMembers($deviceKey);
            if($couponModel['type'] == Coupon::TYPE_MAP[Coupon::TYPE_RECHARGE_RECEIVE]){
                $moneyKey = Coupon::COUPON_MONEY_CACHE . $couponId;
                $couponModel['moneys'] = $this->redis->hGetAll($moneyKey);
            }
        }
        return $this->success($couponModel);
    }

    /**删除营销
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): ResponseInterface
    {
        $info = $this->distributors->getInfo($request);
        if (!$info) {
            return $this->error(code: '400', msg: '登录态失效 请重新登录');
        }
        $couponId = $request->input('coupon_id', 0, 'int');

        $this->coupon->where('id', $couponId)
            ->where('distributor_id', $info['id'])
            ->delete();
        $deviceKey = Coupon::COUPON_DEVICE_CACHE . $couponId;
        $moneyKey = Coupon::COUPON_MONEY_CACHE . $couponId;
        $this->redis->del($deviceKey);
        $this->redis->del($moneyKey);
        return $this->success(msg: '删除活动成功');
    }

    /**获取优惠券使用情况
     * @param RequestInterface $request
     * @return ResponseInterface
     */

    public function getCouponCount(RequestInterface $request):ResponseInterface{
        $couponId = $request->input('coupon_id', 0, 'int');
        $data['all_people'] = DB::table('coupon_records')
            ->where('coupon_id',$couponId)
            ->select(DB::raw('COUNT(DISTINCT user_id) as count'))
            ->first();

        $data['used_people'] = DB::table('coupon_records')
            ->where('coupon_id',$couponId)
            ->whereNotNull('used_at')
            ->select(DB::raw('COUNT(DISTINCT user_id) as count'))
            ->first();
        $data['used_count']['count'] = DB::table('coupon_records')
            ->where('coupon_id',$couponId)
            ->whereNotNull('used_at')
            ->count();
        return $this->success($data);
    }


}
